package cool.taomu.toolkit.service.client.kademlia.service

import com.google.inject.Inject
import cool.taomu.toolkit.service.client.kademlia.utils.ServiceClientPool
import cool.taomu.toolkit.service.kademlia.entity.KPeerNode
import cool.taomu.toolkit.service.kademlia.service.ICheckPeer
import cool.taomu.toolkit.service.kademlia.service.KRoutingTable
import cool.taomu.toolkit.service.kademlia.thrift.Node
import cool.taomu.toolkit.utils.ByteBufferUtils
import java.nio.charset.StandardCharsets
import org.slf4j.LoggerFactory

class CheckPeerImpl implements ICheckPeer {

    val static LOG = LoggerFactory.getLogger(CheckPeerImpl);

    @Inject
    ServiceClientPool clientPool;

    @Inject
    KRoutingTable router;

    override synchronized apply(KPeerNode peer) {
        var opl = clientPool.peerClient(peer, router.localNode, [ client |
            if (client !== null) {
                var node = new Node(router.localNode.host, router.localNode.port)
                var resp = client.ping(node)
                LOG.debug("ping 状态:{}", resp.status)
                var data = ByteBufferUtils.toString(resp.data, StandardCharsets.UTF_8)
                if (resp.status == 200 && data.equals("PONG")) {
                    return true
                }
            }
            return false
        ])
        if (opl.present) {
            return opl.get()
        }
        return false
    }
}
